import { useEffect, useState } from "react";
import { CheckOutlined, CloseOutlined, DownloadOutlined } from "@ant-design/icons";
import type { PaginationProps, TableColumnsType, TableProps } from "antd";
import { Button, Flex, Tag, Tooltip } from "antd";
import Table from "@/components/table";
import CardButton from "./card-button";
import PassModal from "./pass-modal";
import RejectModal from "./reject-modal";
import { passOrder, rejectOrder, useUserOrderList } from "@/api/order";
import { ORDER_REVIEW_STATUS_OPTIONS } from "@/constants/options";

import { UserOrderDataType } from "@/types/order";

type TableRowSelection<T extends object = object> = TableProps<T>["rowSelection"];

export default function OrderDetailTableCard({ id }: { id: number }) {
  const { data, loading: isFetching, runAsync: fetchList, refresh } = useUserOrderList();
  const [currentActionData, setCurrentActionData] = useState<UserOrderDataType | UserOrderDataType[] | null>(
    null,
  );
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRecords, setSelectedRecords] = useState<UserOrderDataType[]>([]);
  const [openPassModal, setOpenPassModal] = useState(false);
  const [openRejectModal, setOpenRejectModal] = useState(false);
  const [batchLoading, setBatchLoading] = useState(false);
  const [pagination, setPagination] = useState({
    current: 1,
    pageSize: 5,
    total: data?.total,
  });

  const columns: TableColumnsType<UserOrderDataType> = [
    {
      title: "用户ID",
      dataIndex: "userId",
      key: "userId",
    },
    {
      title: "用户昵称",
      dataIndex: "phone",
      key: "phone",
    },
    {
      title: "小红书账号",
      dataIndex: "email",
      key: "email",
    },
    {
      title: "小红书主页",
      dataIndex: "website",
      key: "website",
    },
    {
      title: "蒲公英",
      dataIndex: "businessCard",
      key: "businessCard",
      render: (_, record) => (
        <>
          <Button type="link" size="small">
            <a href={record.businessCard.name} target="_blank" rel="noopener noreferrer">
              {record.businessCard.name}
            </a>
          </Button>
        </>
      ),
    },
    {
      title: "名片",
      dataIndex: "businessCard",
      key: "businessCard",
      render: (_, record) => <CardButton data={record.businessCard}>查看名片</CardButton>,
    },
    {
      title: "报名审核",
      dataIndex: "reviewStatus",
      key: "reviewStatus",
      render: (_, record) => {
        const reviewStatus = ORDER_REVIEW_STATUS_OPTIONS.find((item) => item.value === record.reviewStatus);
        if (!reviewStatus) return <Tag color="blue">待审核</Tag>;
        return (
          <>
            <Tag color={reviewStatus?.color}>{reviewStatus?.label}</Tag>
          </>
        );
      },
    },
    {
      title: "已完成商单",
      dataIndex: "createdAt",
      key: "createdAt",
      render: () => "-",
    },
    {
      title: "联系方式",
      dataIndex: "businessCard.mobile",
      key: "businessCard.mobile",
      render: (_, record) => record.businessCard.mobile,
    },
    {
      title: "操作",
      dataIndex: "action",
      key: "action",
      fixed: "right",
      render: (_, record) => {
        return (
          <Flex gap={8}>
            <Tooltip title="通过">
              <Button
                type="primary"
                size="small"
                ghost
                className="p-0"
                icon={<CheckOutlined />}
                loading={batchLoading}
                onClick={() => handleSinglePass(record)}
              />
            </Tooltip>
            <Tooltip title="驳回">
              <Button
                type="primary"
                size="small"
                ghost
                className="p-0"
                icon={<CloseOutlined />}
                loading={batchLoading}
                onClick={() => handleSingleReject(record)}
              />
            </Tooltip>
          </Flex>
        );
      },
    },
  ];

  const canHideColumns: TableColumnsType<UserOrderDataType> = [
    {
      title: "用户ID",
      dataIndex: "userId",
      key: "userId",
    },
    {
      title: "用户昵称",
      dataIndex: "phone",
      key: "phone",
    },
  ];

  const onPageChange = (newPagination: PaginationProps) => {
    const { current, pageSize } = newPagination;
    setPagination({
      ...pagination,
      current: current || 1,
      pageSize: pageSize || 10,
    });
    fetchList({
      pageNum: current || 1,
      pageSize: pageSize || 10,
    });
  };

  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
    // 获取选中的完整记录
    const selectedRecords =
      data?.userBusinessOrders?.filter((item: UserOrderDataType) => newSelectedRowKeys.includes(item.id)) ||
      [];
    setSelectedRecords(selectedRecords);
  };

  const rowSelection: TableRowSelection<UserOrderDataType> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };

  // 检查选中项的状态一致性
  const checkStatusConsistency = (records: UserOrderDataType[]) => {
    if (records.length === 0) return { isConsistent: false, status: null };
    const firstReviewStatus = records[0].reviewStatus;
    const isConsistent = records.every((record) => record.reviewStatus === firstReviewStatus);
    return { isConsistent, status: firstReviewStatus };
  };

  // 批量通过处理
  const handleBatchPass = () => {
    if (selectedRecords.length === 0) {
      window.$message?.warning("请选择要操作的账号");
      return;
    }

    const { isConsistent, status } = checkStatusConsistency(selectedRecords);

    if (!isConsistent) {
      window.$message?.warning("选择的账号状态包含多个绑定状态，需一致哦");
      return;
    }

    switch (status) {
      case "selected": // 已入选
        window.$message?.warning("用户报名已入选");
        break;
      case "rejected": // 未入选 -> 二次确认弹窗
      case "pending": // 待审核 -> 二次确认弹窗
        setCurrentActionData(selectedRecords);
        setOpenPassModal(true);
        break;
    }
  };

  // 批量驳回处理
  const handleBatchReject = () => {
    if (selectedRecords.length === 0) {
      window.$message?.warning("请选择要操作的账号");
      return;
    }
    const { isConsistent, status } = checkStatusConsistency(selectedRecords);
    if (!isConsistent) {
      window.$message?.warning("选择的账号状态包含多个绑定状态，需一致哦");
      return;
    }
    switch (status) {
      case "rejected": // 未入选（已驳回）
        window.$message?.warning("账号已驳回");
        break;
      case "pending": // 待审核 -> 弹窗填写驳回原因
      case "selected": // 已入选 -> 弹窗填写驳回原因
        setCurrentActionData(selectedRecords);
        setOpenRejectModal(true);
        break;
    }
  };

  // 单个通过处理
  const handleSinglePass = (record: UserOrderDataType) => {
    switch (record.reviewStatus) {
      case "selected": // 已入选
        window.$message?.warning("用户账号已入选");
        break;
      case "rejected": // 已驳回 -> 二次确认弹窗
      case "pending": // 待审核 -> 二次确认弹窗
        setCurrentActionData(record);
        setOpenPassModal(true);
        break;
    }
  };

  // 单个驳回处理
  const handleSingleReject = (record: UserOrderDataType) => {
    switch (record.reviewStatus) {
      case "rejected": // 未入选（已驳回）
        window.$message?.warning("用户账号已未入选");
        break;
      case "pending": // 待审核 -> 二次确认弹窗
      case "selected": // 已入选 -> 二次确认弹窗
        setCurrentActionData(record);
        setOpenRejectModal(true);
        break;
    }
  };

  // 执行单个通过
  const handleSinglePass_Confirm = async (record: UserOrderDataType) => {
    setBatchLoading(true);
    try {
      await passOrder(record.id);
      window.$message?.success("审核通过成功");
      refresh();
    } catch {
      window.$message?.error("操作失败");
    } finally {
      setBatchLoading(false);
    }
  };

  // 执行单个驳回
  const handleSingleReject_Confirm = async (record: UserOrderDataType) => {
    setBatchLoading(true);
    try {
      await rejectOrder(record.id);
      window.$message?.success("驳回成功");
      refresh();
    } catch {
      window.$message?.error("操作失败");
    } finally {
      setBatchLoading(false);
    }
  };

  // 执行批量通过
  const handleBatchPass_Confirm = async (records: UserOrderDataType[]) => {
    setBatchLoading(true);
    try {
      const results = await Promise.allSettled(records.map((record) => passOrder(record.id)));
      const successCount = results.filter((result) => result.status === "fulfilled").length;
      const failCount = results.length - successCount;
      if (failCount === 0) {
        window.$message?.success(`成功通过 ${successCount} 个报名`);
        setSelectedRowKeys([]); // 清空选择
        setSelectedRecords([]);
      } else {
        window.$message?.error(`操作完成，成功${successCount}条，失败${failCount}条`);
      }
      refresh();
    } catch {
      window.$message?.error("批量操作失败");
    } finally {
      setBatchLoading(false);
    }
  };

  // 执行批量驳回
  const handleBatchReject_Confirm = async (records: UserOrderDataType[]) => {
    setBatchLoading(true);
    try {
      const results = await Promise.allSettled(records.map((record) => rejectOrder(record.id)));
      const successCount = results.filter((result) => result.status === "fulfilled").length;
      const failCount = results.length - successCount;
      if (failCount === 0) {
        window.$message?.success(`成功驳回 ${successCount} 个报名`);
        setSelectedRowKeys([]); // 清空选择
        setSelectedRecords([]);
      } else {
        window.$message?.error(`操作完成，成功${successCount}条，失败${failCount}条`);
      }
      refresh();
    } catch {
      window.$message?.error("批量操作失败");
    } finally {
      setBatchLoading(false);
    }
  };

  // Modal确认处理 - 通过
  const handlePassConfirm = () => {
    if (!currentActionData) return;
    if (Array.isArray(currentActionData)) {
      // 批量处理
      handleBatchPass_Confirm(currentActionData);
    } else {
      // 单个处理
      handleSinglePass_Confirm(currentActionData);
    }
    setOpenPassModal(false);
    setCurrentActionData(null);
  };

  // Modal确认处理 - 驳回
  const handleRejectConfirm = () => {
    if (!currentActionData) return;
    if (Array.isArray(currentActionData)) {
      // 批量处理
      handleBatchReject_Confirm(currentActionData);
    } else {
      // 单个处理
      handleSingleReject_Confirm(currentActionData);
    }
    setOpenRejectModal(false);
    setCurrentActionData(null);
  };

  const handleExport = () => {
    window.$message?.info("功能正在开发");
  };

  useEffect(() => {
    fetchList({
      businessOrderId: id,
      pageNum: 1,
      pageSize: 1000,
    });
  }, []);

  return (
    <>
      <div className="flex-1 shrink-0 bg-white rounded-lg p-4 overflow-x-auto dark:bg-[#1f1f1f]">
        <h3 className="text-lg font-bold mb-4">
          {data?.total > 0 && <span>共有{data?.total}位达人报名</span>}
        </h3>
        <Table
          rowKey="id"
          columns={columns}
          canHideColumns={canHideColumns}
          dataSource={data?.userBusinessOrders}
          loading={isFetching || batchLoading}
          pagination={{ ...pagination, total: data?.total }}
          rowSelection={rowSelection}
          onChange={onPageChange}
          onRefresh={refresh}
          leftActions={
            <>
              <Button
                size="middle"
                type="primary"
                disabled={selectedRowKeys.length === 0}
                onClick={handleBatchPass}
                loading={batchLoading}
              >
                通过
              </Button>
              <Button
                size="middle"
                type="primary"
                ghost
                disabled={selectedRowKeys.length === 0}
                onClick={handleBatchReject}
                loading={batchLoading}
              >
                驳回
              </Button>
              <Button size="middle" type="primary" ghost icon={<DownloadOutlined />} onClick={handleExport}>
                导出
              </Button>
            </>
          }
        />
      </div>
      <PassModal
        data={currentActionData}
        open={openPassModal}
        loading={batchLoading}
        onCancel={() => {
          setOpenPassModal(false);
          setCurrentActionData(null);
        }}
        onOk={handlePassConfirm}
      />
      <RejectModal
        data={currentActionData}
        open={openRejectModal}
        loading={batchLoading}
        onCancel={() => {
          setOpenRejectModal(false);
          setCurrentActionData(null);
        }}
        onOk={handleRejectConfirm}
      />
    </>
  );
}
